//从前序与中序遍历序列构造二叉树
public class code1 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
    //preIndex得为成员变量，因为递归的过程中index不会++，归的时候还是原来的preIndex
    public int preIndex ;
    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inBegin,int inEnd) {
        //递归的结束条件
        if(inBegin>inEnd) return null;
        //1.创建根节点
        TreeNode root = new TreeNode(preorder[preIndex]);
        //2.在中序遍历的数组中找到前序当前节点的下标
        int rootIndex = findRootIndex(inorder,inBegin,inEnd,preorder[preIndex]);
        preIndex++;
        //3.分别创建左子树和右子树
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inEnd);
        return root;

    }
    //在中序遍历的数组中找到前序对应的元素
    public int findRootIndex(int[] inorder,int inBegin,int inEnd,int key) {
        for(int i=inBegin;i<=inEnd;i++) {
            if(key==inorder[i]) {
                return i;
            }
        }
        return -1;
    }
}
